import { useState, useRef, useEffect } from "react";
import { useTheme } from "@/hooks/useTheme";
import { toast } from "sonner";
import { motion } from "framer-motion";

// 运镜类型
interface CameraMovement {
  id: string;
  name: string;
  description: string;
  icon: string;
}

// 运镜预设
const cameraMovements: CameraMovement[] = [
  {
    id: "static",
    name: "固定视角",
    description: "保持稳定的拍摄角度",
    icon: "fa-video"
  },
  {
    id: "pan",
    name: "平移",
    description: "水平移动相机",
    icon: "fa-arrows-left-right"
  },
  {
    id: "tilt",
    name: "俯仰",
    description: "垂直移动相机",
    icon: "fa-arrows-up-down"
  },
  {
    id: "dolly",
    name: "推拉",
    description: "前后移动相机",
    icon: "fa-arrow-right-arrow-left"
  },
  {
    id: "orbit",
    name: "360度环绕",
    description: "围绕主体旋转拍摄",
    icon: "fa-circle-notch"
  },
  {
    id: "bullet-time",
    name: "子弹时间",
    description: "冻结时间，旋转视角",
    icon: "fa-bolt"
  }
];

// 分辨率选项
const resolutionOptions = [
  { id: "1080p", name: "1080P", value: "1920x1080" },
  { id: "4k", name: "4K", value: "3840x2160" }
];

// 帧率选项
const fpsOptions = [
  { id: "24fps", name: "24 FPS", value: 24 },
  { id: "30fps", name: "30 FPS", value: 30 }
];

// 视频比例选项
const aspectRatioOptions = [
  { id: "16-9", name: "16:9", value: "16/9" },
  { id: "1-1", name: "1:1", value: "1/1" },
  { id: "9-16", name: "9:16", value: "9/16" }
];

const VideoGenerator = () => {
  const { isDark } = useTheme();
  const [prompt, setPrompt] = useState<string>("");
  const [selectedMovement, setSelectedMovement] = useState<string>("static");
  const [selectedResolution, setSelectedResolution] = useState<string>("4k");
  const [selectedFps, setSelectedFps] = useState<string>("24fps");
  const [selectedAspectRatio, setSelectedAspectRatio] = useState<string>("16-9");
  const [uploadedFiles, setUploadedFiles] = useState<Array<{ name: string; type: string; preview: string }>>([]);
  const [isDragOver, setIsDragOver] = useState<boolean>(false);
  const [isGenerating, setIsGenerating] = useState<boolean>(false);
  const [progress, setProgress] = useState<number>(0);
  const [generationStep, setGenerationStep] = useState<string>("初始化");
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isLoading, setIsLoading] = useState<boolean>(false);

  // 清理URL对象，防止内存泄漏
  useEffect(() => {
    return () => {
      uploadedFiles.forEach(file => {
        URL.revokeObjectURL(file.preview);
      });
    };
  }, [uploadedFiles]);

  // 处理文件拖放
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(true);
  };

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
    
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      handleFiles(e.dataTransfer.files);
    }
  };

  // 处理文件选择
  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      handleFiles(e.target.files);
    }
  };

  // 处理文件上传逻辑
  const handleFiles = (files: FileList) => {
    setIsLoading(true);
    
    // 模拟文件上传进度
    setTimeout(() => {
      const newFiles: Array<{ name: string; type: string; preview: string }> = [];
      
      Array.from(files).forEach(file => {
        // 检查文件类型
        if (!file.type.match('image.*') && !file.type.match('video.*')) {
          toast.error("请上传图片或视频文件");
          return;
        }
        
        // 检查文件大小（限制10MB）
        if (file.size > 10 * 1024 * 1024) {
          toast.error("文件大小不能超过10MB");
          return;
        }
        
        // 创建预览URL
        const previewUrl = URL.createObjectURL(file);
        
        newFiles.push({
          name: file.name,
          type: file.type.startsWith('image/') ? 'image' : 'video',
          preview: previewUrl
        });
      });
      
      setUploadedFiles(prev => [...prev, ...newFiles]);
      
      if (newFiles.length > 0) {
        toast.success(`已添加 ${newFiles.length} 个文件`);
      }
      
      setIsLoading(false);
    }, 800);
  };

  // 移除上传的文件
  const removeFile = (index: number) => {
    const fileToRemove = uploadedFiles[index];
    URL.revokeObjectURL(fileToRemove.preview);
    
    setUploadedFiles(prev => prev.filter((_, i) => i !== index));
    toast.info("已移除文件");
  };

  // 触发文件选择对话框
  const triggerFileInput = () => {
    if (!isLoading) {
      fileInputRef.current?.click();
    }
  };

  // 生成视频
  const generateVideo = () => {
    // 验证表单
    if (!prompt.trim()) {
      toast.error("请输入视频描述");
      return;
    }
    
    if (uploadedFiles.length === 0) {
      toast.warning("建议上传参考图片或视频以获得更好的效果");
    }
    
    setIsGenerating(true);
    setProgress(0);
    setGenerationStep("初始化模型");
    
    // 模拟视频生成进度
    let currentProgress = 0;
    const interval = setInterval(() => {
      currentProgress += 5;
      setProgress(currentProgress);
      
      // 更新生成步骤
      if (currentProgress < 20) {
        setGenerationStep("初始化模型");
      } else if (currentProgress < 40) {
        setGenerationStep("处理输入数据");
      } else if (currentProgress < 70) {
        setGenerationStep("FP8量化推理中");
      } else if (currentProgress < 90) {
        setGenerationStep("xDiT多卡并行渲染");
      } else {
        setGenerationStep("视频后处理");
      }
      
      if (currentProgress >= 100) {
        clearInterval(interval);
        
        // 模拟生成完成
        setTimeout(() => {
          setIsGenerating(false);
          toast.success("视频生成成功！");
          
          // 在实际应用中，这里会跳转到视频预览页面或添加到项目列表
          setTimeout(() => {
            window.location.href = "/my-projects";
          }, 1500);
        }, 500);
      }
    }, 300);
  };

  // 示例提示词
  const examplePrompts = [
    "阳光明媚的海滩日落，波浪轻轻拍打着岸边，金色的阳光洒在海面上",
    "未来城市的夜景，高楼大厦霓虹闪烁，飞行汽车在城市中穿梭",
    "森林中的小溪，清澈的水流过石头，周围环绕着茂密的树木和各种野生动物",
    "太空站外的宇航员进行太空行走，背景是地球和无尽的星空"
  ];

  // 动画变体
  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.05
      }
    }
  };

  const itemVariants = {
    hidden: { opacity: 0, y: 10 },
    visible: {
      opacity: 1,
      y: 0,
      transition: {
        duration: 0.3
      }
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.5 }}
      className={`rounded-2xl p-6 md:p-8 ${isDark ? 'glass-effect-dark' : 'glass-effect'} shadow-xl`}
    >
      <h2 className="text-2xl font-bold mb-6">创建AI视频 <span className="text-sm font-normal text-indigo-400">（HunyuanVideo 130亿参数模型）</span></h2>
      
      {/* 文本提示输入框 */}
      <div className="mb-6">
        <label htmlFor="prompt" className="block text-sm font-medium mb-2">
          视频描述
        </label>
        <textarea
          id="prompt"
          value={prompt}
          onChange={(e) => setPrompt(e.target.value)}
          placeholder="描述您想要生成的视频内容，越详细效果越好"
          className={`w-full h-32 px-4 py-3 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 resize-none ${
            isDark 
              ? 'bg-slate-800/80 border border-slate-700 placeholder-slate-500' 
              : 'bg-white/80 border border-slate-200 placeholder-slate-400'
          }`}
        />
        
        {/* 示例提示词 */}
        <motion.div 
          className="mt-3 flex flex-wrap gap-2"
          variants={containerVariants}
          initial="hidden"
          animate="visible"
        >
          {examplePrompts.map((example, index) => (
            <motion.button
              key={index}
              variants={itemVariants}
              onClick={() => setPrompt(example)}
              className={`text-xs px-3 py-1 rounded-full ${
                isDark 
                  ? 'bg-slate-800 hover:bg-slate-700' 
                  : 'bg-white/80 hover:bg-slate-100'
              } text-slate-300`}
            >
              {example.length > 20 ? example.substring(0, 20) + '...' : example}
            </motion.button>
          ))}
        </motion.div>
      </div>
      
      {/* 视频设置 - 分辨率和帧率 */}
      <div className="mb-6 grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium mb-2">
            分辨率
          </label>
          <div className="grid grid-cols-2 gap-2">
            {resolutionOptions.map(option => (
              <button
                key={option.id}
                onClick={() => setSelectedResolution(option.id)}
                className={`py-2 rounded-lg text-center transition-all duration-300 ${
                  selectedResolution === option.id
                    ? 'bg-indigo-600 text-white shadow-lg'
                    : `${isDark ? 'bg-slate-800 hover:bg-slate-700' : 'bg-white/80 hover:bg-slate-100'} shadow`
                }`}
              >
                {option.name}
              </button>
            ))}
          </div>
        </div>
        
        <div>
          <label className="block text-sm font-medium mb-2">
            帧率
          </label>
          <div className="grid grid-cols-2 gap-2">
            {fpsOptions.map(option => (
              <button
                key={option.id}
                onClick={() => setSelectedFps(option.id)}
                className={`py-2 rounded-lg text-center transition-all duration-300 ${
                  selectedFps === option.id
                    ? 'bg-indigo-600 text-white shadow-lg'
                    : `${isDark ? 'bg-slate-800 hover:bg-slate-700' : 'bg-white/80 hover:bg-slate-100'} shadow`
                }`}
              >
                {option.name}
              </button>
            ))}
          </div>
        </div>
      </div>
      
      {/* 视频比例 */}
      <div className="mb-6">
        <label className="block text-sm font-medium mb-2">
          视频比例
        </label>
        <div className="grid grid-cols-3 gap-2">
          {aspectRatioOptions.map(option => (
            <button
              key={option.id}
              onClick={() => setSelectedAspectRatio(option.id)}
              className={`py-2 rounded-lg text-center transition-all duration-300 ${
                selectedAspectRatio === option.id
                  ? 'bg-indigo-600 text-white shadow-lg'
                  : `${isDark ? 'bg-slate-800 hover:bg-slate-700' : 'bg-white/80 hover:bg-slate-100'} shadow`
              }`}
            >
              {option.name}
            </button>
          ))}
        </div>
      </div>
      
      {/* 运镜选择 */}
      <div className="mb-6">
        <label className="block text-sm font-medium mb-3">
          选择运镜方式
        </label>
        <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
          {cameraMovements.map(movement => (
            <button
              key={movement.id}
              onClick={() => setSelectedMovement(movement.id)}
              className={`p-3 rounded-xl text-left transition-all duration-300 ${
                selectedMovement === movement.id
                  ? 'bg-indigo-600 text-white shadow-lg'
                  : `${isDark ? 'bg-slate-800 hover:bg-slate-700' : 'bg-white/80 hover:bg-slate-100'} shadow`
              }`}
            >
              <div className="flex items-center mb-1">
                <i className={`fa-solid ${movement.icon} mr-2`}></i>
                <span className="font-medium">{movement.name}</span>
              </div>
              <p className="text-xs opacity-80">{movement.description}</p>
            </button>
          ))}
        </div>
      </div>
      
      {/* 文件上传区域 */}
      <div className="mb-6">
        <label className="block text-sm font-medium mb-2">
          上传参考图片/视频（可选）
        </label>
        <div 
          onClick={triggerFileInput}
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onDrop={handleDrop}
          className={`border-2 border-dashed p-6 rounded-xl text-center cursor-pointer transition-all duration-300 ${
            isDragOver 
              ? 'border-indigo-500 bg-indigo-900/20 drag-active' 
              : `${isDark ? 'border-slate-700 hover:border-indigo-500' : 'border-slate-300 hover:border-indigo-500'}`
          } ${isDark ? 'bg-slate-800/50' : 'bg-white/50'}`}
          style={{ pointerEvents: isLoading ? 'none' : 'auto' }}
        >
          {isLoading ? (
            <>
              <i className="fa-solid fa-spinner fa-spin text-3xl mb-3"></i>
              <p className="mb-1 font-medium">正在上传...</p>
            </>
          ) : (
            <>
              <i className="fa-solid fa-cloud-arrow-up text-3xl mb-3"></i>
              <p className="mb-1 font-medium">拖放文件到此处或点击上传</p>
              <p className="text-xs opacity-70">支持 JPG、PNG、MP4 格式，单文件不超过10MB</p>
            </>
          )}
          <input
            ref={fileInputRef}
            type="file"
            multiple
            accept="image/*,video/*"
            onChange={handleFileSelect}
            className="hidden"
            disabled={isLoading}
          />
        </div>
      </div>
      
      {/* 已上传文件预览 */}
      {uploadedFiles.length > 0 && (
        <div className="mb-6">
          <h3 className="text-sm font-medium mb-3">已上传文件</h3>
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
            {uploadedFiles.map((file, index) => (
              <div 
                key={index} 
                className={`relative rounded-lg overflow-hidden ${file.type === 'video' ? 'aspect-video' : 'aspect-square'}`}
              >
                {file.type === 'image' ? (
                  <img 
                    src={file.preview} 
                    alt={file.name} 
                    className="w-full h-full object-cover"
                  />
                ) : (
                  <div className="w-full h-full bg-slate-900 flex items-center justify-center">
                    <i className="fa-solid fa-film text-white text-3xl"></i>
                  </div>
                )}
                <button
                  onClick={() => removeFile(index)}
                  className="absolute top-1 right-1 p-1.5 bg-black/60 text-white rounded-full hover:bg-red-600 transition-colors"
                  aria-label="删除文件"
                >
                  <i className="fa-solid fa-xmark text-xs"></i>
                </button>
                <div className="absolute bottom-0 left-0 right-0 p-1 bg-gradient-to-t from-black/80 to-transparent">
                  <p className="text-xs text-white truncate">{file.name}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
      
      {/* 生成按钮和进度条 */}
      <div className="pt-4 border-t border-slate-700/50">
        {isGenerating ? (
          <div>
            <div className="flex justify-between items-center mb-2">
              <span>{generationStep}</span>
              <span>{progress}%</span>
            </div>
            <div className={`h-2.5 rounded-full overflow-hidden ${isDark ? 'bg-slate-700' : 'bg-slate-200'} mb-4`}>
              <motion.div 
                className="h-full bg-gradient-to-r from-indigo-500 to-purple-500 rounded-full"
                initial={{ width: "0%" }}
                animate={{ width: `${progress}%` }}
                transition={{ duration: 0.3 }}
              />
            </div>
            
            {/* 生成信息 */}
            <div className={`text-xs ${isDark ? 'text-slate-400' : 'text-slate-500'} flex justify-between`}>
              <div>
                <span className="font-medium">模型:</span> HunyuanVideo 130亿参数
              </div>
              <div>
                <span className="font-medium">优化:</span> FP8量化推理
              </div>
            </div>
          </div>
        ) : (
          <button
            onClick={generateVideo}
            className="w-full py-3 rounded-xl bg-gradient-to-r from-indigo-600 to-purple-600 text-white font-medium shadow-lg hover:shadow-xl transition-all duration-300 transform hover:-translate-y-0.5"
          >
            生成视频
            <i className="fa-solid fa-magic ml-2"></i>
          </button>
        )}
      </div>
    </motion.div>
  );
};

export default VideoGenerator;